package com.yuke.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.base.exception.BusinessException;
import com.yuke.cloud.common.core.interceptor.CoreHeaderInterceptor;
import com.yuke.cloud.common.core.utils.RequestUtil;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.zuul.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class AuthHeaderFilter extends ZuulFilter {

    private static final String BEARER_TOKEN_TYPE = "bearer ";
    private static final String OPTIONS = "OPTIONS";
    private static final String AUTH_PATH = "/auth";
    private static final String LOGOUT_URI = "/oauth/token";
    private static final String ALIPAY_CALL_URI = "/order/pay/notify";
    private static final String WEIXINPAY_CALL_URI = "/wxpay/notifyWeiXinPay";
    private static final String ALIPAY_RECHARGE_CALL_URI = "/bill/billpay/AliNotify";// add by zn 20191212
    private static final String WEIXINPAY_RECHARGE_CALL_URI = "/bill/billpay/WxNotify";// add by wg 20191212
    private static final String MALL_PATH = "/mall";  // add by wg 20181229 增加/mall的情况时不用认证
    private static final String WS_PATH = "/webSocketServer";  // add by wg 20190104 增加websocket连接不用认证
    private static final String SWAGGER_URI = "/v2/api-docs";

    /**
     * Filter type string.
     *
     * @return the string
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * Filter order int.
     *
     * @return the int
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * Should filter boolean.
     *
     * @return the boolean
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * Run object.
     *
     * @return the object
     */
    @Override
    public Object run() {
        log.info("AuthHeaderFilter - 开始鉴权...");
        RequestContext requestContext = RequestContext.getCurrentContext();
        try {
            doSomething(requestContext);
        } catch (Exception e) {
            log.error("AuthHeaderFilter - [FAIL] EXCEPTION={}", e.getMessage(), e);
            throw new BusinessException(ErrorCodeEnum.UAC10011041);
        }
        return null;
    }

    private void doSomething(RequestContext requestContext) throws ZuulException {
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();
        log.info("ZUUL-AuthHeaderFilter-doSomethiing - request...{}",request);
        if (OPTIONS.equalsIgnoreCase(request.getMethod()) || requestURI.contains(AUTH_PATH)
                || requestURI.contains(LOGOUT_URI) || requestURI.contains(ALIPAY_CALL_URI)
                || requestURI.contains(WEIXINPAY_CALL_URI) || requestURI.contains(MALL_PATH)
                || requestURI.contains(ALIPAY_RECHARGE_CALL_URI) || requestURI.contains(WEIXINPAY_RECHARGE_CALL_URI)
                || requestURI.contains(WS_PATH)||requestURI.contains(SWAGGER_URI)) {

            //add by wg 20190107 对包含/mall的请求，由于不需要token认证，如果header中包含了token，则去掉
            if (requestURI.contains(MALL_PATH)) {
                String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
                if (PublicUtil.isNotEmpty(authHeader)) {
                    HttpUtil.delReqHeader(request, HttpHeaders.AUTHORIZATION);
                } else {
                    authHeader = request.getHeader("authorization");
                    if (PublicUtil.isNotEmpty(authHeader)) {
                        HttpUtil.delReqHeader(request, "authorization");
                    }
                }
            }

            return;
        }
        String authHeader = RequestUtil.getAuthHeader(request);

        if (PublicUtil.isEmpty(authHeader)) {
            throw new ZuulException("刷新页面重试", 403, "check token fail");
        }


        if (StringUtils.startsWithIgnoreCase(authHeader, BEARER_TOKEN_TYPE)) {
            requestContext.addZuulRequestHeader(HttpHeaders.AUTHORIZATION, authHeader);

            log.info("authHeader={} ", authHeader);
            // 传递给后续微服务
            requestContext.addZuulRequestHeader(CoreHeaderInterceptor.HEADER_LABEL, authHeader);
        }
    }
}
